<?php

namespace addons\exam\controller;


use app\common\model\MoneyLog;

class Userwalletapply extends Base
{

    protected $noNeedLogin = ['rule'];
    protected $noNeedRight = ['*'];


    public function index()
    {
        $this->success('提现记录', \addons\exam\model\UserWalletApply::getList($this->auth->id));
    }


    public function apply () {
        $money = $this->request->post('money');
        $config = \addons\exam\model\UserWalletApply::getWithdrawConfig();


        $min = round(floatval($config['wallet_min']), 2);
        $max = round(floatval($config['wallet_max']), 2);
        $service_fee = round(floatval($config['service_fee']), 3);      // 三位小数

        // 检查最小提现金额
        if (bccomp($money, $min) === -1 || $money <= 0) {
            $this->error('提现金额不能少于 ' . $min . '元');
        }

        // 检查最大提现金额
        if ($max && bccomp($money, $max) === 1 ) {
            $this->error('提现金额不能大于 ' . $max . '元');
        }

        // 计算手续费
        $charge = bcmul($money, $service_fee, 2);
        if (bccomp($this->auth->money, $charge + $money) === -1) {
            $this->error('可提现余额不足');
        }
        $apply = \addons\exam\model\UserWalletApply::apply($this->auth->id,$money,$charge,$service_fee);
        if ($apply) {
            $this->success('申请成功');
        }
        $this->error('申请失败');
    }


    public function rule () {
        // 提现规则
        $config = \addons\groupon\model\UserWalletApply::getWithdrawConfig();
        $min = round(floatval($config['min']), 2);
        $max = round(floatval($config['max']), 2);
        $service_fee = floatval($config['service_fee']) * 100;
        $service_fee = round($service_fee, 1);      // 1 位小数

        $rule = [
            'min' => $min,
            'max' => $max,
            'service_fee' => $service_fee,
            'methods' => $config['methods'] ?? []
        ];

        $this->success('提现规则', $rule);
    }

    /**
     * 明细
     */

    public function detail(){
        $type = input('type','DZ');
        $moneylogModel = new MoneyLog();
        $where['user_id'] = $this->auth->id;
        $where['memo'] = $moneylogModel->getKindList()[$type];
        $data = MoneyLog::where($where)->field('id,money,before,after,createtime')->order('id desc')->paginate(10,true);
        $this->success('ok',$data);
    }

}
